package com.slh.touchandroid.adapter;

import java.util.List;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.slh.touchandroid.R;
import com.slh.touchandroid.utils.AppUtils;

public class AppAdapter extends BaseAdapter {
	private Context context;
	private List<ApplicationInfo> applications;
	private int resId;

	public AppAdapter(Context context, List<ApplicationInfo> mApplicationInfos,
			int resId) {
		super();
		this.context = context;
		this.applications = mApplicationInfos;
		this.resId = resId;
	}

	@Override
	public int getCount() {
		return applications.size();
	}

	@Override
	public Object getItem(int position) {
		return applications.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Holder holder;
		if (null == convertView) {
			convertView = LayoutInflater.from(context).inflate(resId, null);
			holder = new Holder();
			holder.tvName = (TextView) convertView.findViewWithTag(context
					.getString(R.string.tag_name));
			convertView.setTag(holder);
		} else {
			holder = (Holder) convertView.getTag();
		}
		ApplicationInfo application = applications.get(position);
		holder.tvName.setText(AppUtils
				.getApplicationLabel(context, application));
		Drawable drawable = AppUtils.getApplicationIcon(context, application);
		drawable.setBounds(0, 0, 64, 64);
		holder.tvName.setCompoundDrawables(drawable, null, null, null);
		return convertView;
	}

	private static class Holder {
		TextView tvName;
	}

}
